package com.example.utils;

import com.example.exception.ServiceException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha256Util {
    /**
     * 通常用作保存到数据库前的加密
     * @param str 需要hash计算的字符串
     * @return 加密后的字符串
     */
    public static String encryption(String str) {
        try {
            // 创建SHA-256实例
            MessageDigest md = MessageDigest.getInstance("SHA-256");

            // 计算文本的SHA-256哈希值
            byte[] hashBytes = md.digest(str.getBytes());

            // 将字节数组转换为16进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new ServiceException(ResultCodeUtil.FORBIDDEN,"密码加密异常");
        }
    }
}
